# coding:utf-8
"""mongo users"""
from mongo import users, tokens
from flask_restful import Resource
from bson import json_util
from bson.json_util import dumps
from flask import Response, request
import pymongo
import uuid
import datetime
import hashlib


class Login(Resource):

    def post(self):
        login_info = request.get_json()
        count = users.count({'name': login_info['name'], 'pwd': login_info['pwd']})
        print(count)
        if (1 == count):
            token = self.get_token(login_info['name'])
            upt_result = tokens.update_one(
                {'uname': login_info['name']}, {'$set': token}, upsert=True)
            if (upt_result.upserted_id or upt_result.modified_count):
                return Response(dumps(token), 200)
            else:
                return Response('false', 501)

        else:
            return Response('false', 500)

    def get_token(self, uname):
        d = datetime.datetime.utcnow() + datetime.timedelta(days=1)
        token = {'uname': uname, 'token': uuid.uuid1(), 'expire': d}
        return token

class Token(Resource):

    def get(self, token):
        if (token):
            t = tokens.find_one({'token': uuid.UUID(token)})
            if (t and t['expire'] > datetime.datetime.utcnow()):
                return Response(dumps({'status': 'true'}), 200)

        return Response(dumps({'status': 'false'}), 500)
